package com.xuecheng.media.service.jobhandler;

import com.xuecheng.base.constant.MediaProcessConstant;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.IMediaProcessService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @description 超时处理任务
 * @author 勾新杰
 * @version 1.0
 * @date 2025/2/13 16:38
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ExceedTimeJob {

    /**
     * 媒资处理服务
     */
    private final IMediaProcessService mediaProcessService;

    /**
     * 超时处理任务
     */
    @XxlJob("exceedTimeJobHandler")
    public void exceedTimeJobHandler() {
        // 1. 获取超时处理列表
        List<MediaProcess> mediaProcessList = mediaProcessService.listExceedTimeProcess();
        if (mediaProcessList == null || mediaProcessList.isEmpty()) return;
        // 2. 遍历超时处理列表，更新状态为失败，如果失败次数已满则记录失败原因为超时
        mediaProcessList.forEach(
                mediaProcess -> {
                    Integer failCount = mediaProcessService.fail(mediaProcess.getId());
                    if (Objects.equals(failCount, MediaProcessConstant.MAX_FAIL_COUNT))
                        mediaProcessService.failProcess(mediaProcess.getId(), "已是最大失败次数，最后一次失败原因：超时");
                }
        );
    }
}
